package com.fubowen.reader.adapter

import androidx.lifecycle.LifecycleCoroutineScope
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fubowen.reader.db.model.Tree
import com.fubowen.reader.extension.getFileList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FileExplorerPagingSource(val book: Tree, private val lifecycleScope: LifecycleCoroutineScope, val adapter: TreeAdapter) : PagingSource<Int, Tree>() {
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Tree> {
        return try {

            val pageIndex = params.key ?: 1
            val pageSize = params.loadSize
            val skipCount = (pageIndex - 1) * pageSize
            getFileList(book)
            lifecycleScope.launch {
                withContext(Dispatchers.IO) {
                    book.children.forEach { getFileList(it) }
                }
            }
            val fromIndex = skipCount.coerceIn(0, book.children.size)
            val toIndex = (skipCount + pageSize).coerceIn(0, book.children.size)
            val list = book.children.subList(fromIndex, toIndex)

            LoadResult.Page(
                data = list,
                prevKey = if (pageIndex == 1) null else pageIndex.minus(1),
                nextKey = if (list.isEmpty()) null else pageIndex.plus(1)
            )
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }

    override fun getRefreshKey(state: PagingState<Int, Tree>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }
}



